package com.seal.yoyoshop.adminweb;

import com.seal.yoyoshop.bin.User;
import com.seal.yoyoshop.service.UserService;
import com.seal.yoyoshop.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "UserEditServlet", value = "/admin/userEdit")
public class UserEditServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("flag",2);

        String idstr = request.getParameter("id");
        int id = Integer.parseInt(idstr);
        User user = userService.getUserById(id);
        request.setAttribute("user",user);


        request.getRequestDispatcher("/admin/user_edit.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String idstr = request.getParameter("id");
        int id = Integer.parseInt(idstr);
        User user = userService.getUserById(id);
        String name = request.getParameter("name");
        if(name.length() > 30){
            request.setAttribute("msg","添加失败，姓名过长");
            request.getRequestDispatcher("/admin/user_edit.jsp").forward(request, response);
            return;
        }
        String phone = request.getParameter("phone");
        try {
            long phoneLong = Long.parseLong(phone);
        }catch (Exception e) {
            request.setAttribute("msg","添加失败，手机号错误");
            request.getRequestDispatcher("/admin/user_add.jsp").forward(request, response);
            return;
        }
        String address = request.getParameter("address");
        if(address.length() > 100){
            request.setAttribute("msg","添加失败，家庭住址过长");
            request.getRequestDispatcher("/admin/user_add.jsp").forward(request, response);
            return;
        }
//        更新用户
        user.setName(name);
        user.setPhone(phone);
        user.setAddress(address);
        boolean isSuccess = userService.updateUser(user);

        response.sendRedirect("userList?page=1&size=16");

    }
}
